<template>
  <div class="fileup">
    <div class="custom">
      <span class="lb">自定义文件上传例子:</span>
      <label>
        <input type="file" @change="fileChange($event)" />点击上传
      </label>
    </div>

    <div class="ele">
      <span class="lb">element-ui文件上传例子:</span>
      <el-upload
        class="upload-video"
        action
        :limit="1"
        :file-list="files"
        :http-request="videoUpload"
        :on-remove="onremove"
        :on-exceed="onExceed"
        ref="upfile"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </div>
   <div class="custom">
      <span class="lb">使用base64上传的例子:</span>
      <label>
        <input type="file" @change="baseChange($event)" />点击上传
      </label>
    </div>
    <div class="result" v-if="result">
      <img :src="result" alt />
    </div>
  </div>
</template>
<script>
export default {
  name: "fileup",
  data() {
    return {
      result: "",
      files: []
    };
  },
  mounted() {},
  methods: {
    async fileChange(e) {
      let target = e.target.cloneNode();
      e.target.value = "";
      let file = target.files[0];
      let fd = new FormData();
      fd.append("file", file);
      let res = await this.$api.uploadfile(fd);
      this.result =  res.url ; //提交到数据库保存的时候，只需要保存 res.name
    },
    onUploadProgress(params,e){
      //加入上传进度
      let percent = parseInt(e.loaded / e.total * 100)  || 0;
      params.onProgress({percent:`${percent}%`});
    },
    async videoUpload(params) {
      const me = this;
      me.disabled = true;
      let file = params.file;
      let fd = new FormData(); // 创建form对象
      fd.append("file", file); // 通过append向form对象添加数据
      let res = await this.$api.uploadfile(fd,{onUploadProgress:me.onUploadProgress.bind(me,params)});
      this.result =  res.url ; //提交到数据库保存的时候，只需要保存 res.name

    },
    onremove(file, fileList) {
      const me = this;
      //删除
      console.log("删除", file);
    },
    onExceed(files, fileList) {
      const me = this;
      me.$message.warning("先删除之前的文件");
    },
    async baseChange(e){
      // 上传 base 64 的图片
      let target = e.target.cloneNode();
      e.target.value = "";
      let file = target.files[0];
      let imgData = await this.$utils.fileRead(file);
      let res = await this.$api.uploadImgData({imgData});
      this.result =  res.url ; // 提交到数据库保存的时候，只需要保存 res.name
    }
  }
};
</script>
<style lang="scss" scoped>
.fileup {
  text-align: center;
  padding-top: 20px;
  span.lb {
    margin-right: 10px;
  }
  input[type="file"] {
    display: none;
  }
  label {
    display: inline-block;
    width: 90px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    background: #409eff;
    color: #fff;
    border-radius: 4px;
    cursor: pointer;
  }
  div.ele {
    margin: 10px 0;
    div.upload-video {
      display: inline-block;
    }
  }
  div.result {
    img {
      max-width: 200px;
    }
  }
}
</style>